package cn.swenty.backstage.framework.service;

import java.util.Iterator;
import java.util.Set;

import javax.inject.Inject;

import org.springframework.data.redis.core.RedisTemplate;

import cn.swenty.backstage.framework.common.FormMap;
import cn.swenty.backstage.framework.database.annotation.TableSeg;

public abstract class RedisFormService extends BaseService {
	
	@Inject
	private RedisTemplate redisTemplate;
	
	
	public <T extends FormMap> void modify2redis(T t) {
		String key = getObjectKey(t);
        redisTemplate.opsForHash().put(t.getClass().getName(), t.get(key), t);  
    }  
  
    public <T extends FormMap> void deleteById2redis(T t) { 
    	String key = getObjectKey(t);
        redisTemplate.opsForHash().delete(t.getClass().getName(), t.get(key));
    }  
  
    public <T extends FormMap> T get2redis(T t) {
    	String key = getObjectKey(t);
    	return (T) redisTemplate.opsForHash().get(t.getClass().getName(), t.get(key));  
        
    }  
    
    public <T extends FormMap> void modify2redis(T t,String key) {
        redisTemplate.opsForHash().put(t.getClass().getName(), t.get(key), t);  
    }  
	
    public <T extends FormMap> void deleteById2redis(T t,String key) { 
        redisTemplate.opsForHash().delete(t.getClass().getName(), key);
    }  
    
    public <T extends FormMap> T get2redis(Class<? extends FormMap> c,String key) {
    	return (T) redisTemplate.opsForHash().get(c.getName(), key);  
        
    }
    
    public void removeAll(Class<? extends FormMap> c){
		Set<Object> set = redisTemplate.opsForHash().keys(c.getName());
		if(set.size()>0){
			Iterator<Object> iterator =  set.iterator();
			while(iterator.hasNext()){
				redisTemplate.opsForHash().delete(c.getName(),iterator.next());
			}
		}
	
    }
    
	protected <T extends FormMap> String getObjectKey(T t){
		boolean flag = t.getClass().isAnnotationPresent(TableSeg.class); // 某个类是不是存在TableSeg注解
		if (flag) {
			TableSeg table = (TableSeg) t.getClass().getAnnotation(TableSeg.class);
			return table.id();
		}
		return null;
	}
}
